﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Data;

namespace SPWebsDataSource
{
    public class SPWebsDataSource : DataSourceControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ParameterCollection SelectParameters { get; set; }

        public SPWebsDataSource()
        {
            SelectParameters = new ParameterCollection();
        }

        protected override DataSourceView GetView(string viewName)
        {
            return new SPWebsDataSourceView(this, viewName);
        }

        public event EventHandler DataSourceChanged;

        public System.Collections.ICollection GetViewNames()
        {
            throw new NotImplementedException();
        }
    }

    public class SPWebsDataSourceView : DataSourceView
    {
        IDataSource DataSourceOwner { get; set; }

        public SPWebsDataSourceView(IDataSource dataSourceOwner, string viewName)
            : base(dataSourceOwner, viewName)
        {
            DataSourceOwner = dataSourceOwner;
        }

        protected override System.Collections.IEnumerable ExecuteSelect(DataSourceSelectArguments selectArguments)
        {
            DataTable dataTable = new DataTable();
            Parameter webIdParameter = (DataSourceOwner as SPWebsDataSource).SelectParameters["WebId"];
            Parameter webUrlParameter = (DataSourceOwner as SPWebsDataSource).SelectParameters["WebURL"];
            Parameter recurseParameter = (DataSourceOwner as SPWebsDataSource).SelectParameters["Recurse"];
            Parameter includeRootWebParameter = (DataSourceOwner as SPWebsDataSource).SelectParameters["IncludeRootWeb"];
            SPWeb rootWeb = null;
            if (webIdParameter != null && !string.IsNullOrEmpty(webIdParameter.DefaultValue))
            {
                if (webIdParameter.DefaultValue.Equals("rootweb", StringComparison.CurrentCultureIgnoreCase))
                {
                    rootWeb = SPContext.Current.Site.RootWeb;
                }
                else if (webIdParameter.DefaultValue.Equals("subweb", StringComparison.CurrentCultureIgnoreCase))
                {
                    rootWeb = SPContext.Current.Web;
                }
                else
                {
                    rootWeb = SPContext.Current.Site.AllWebs[new Guid(webIdParameter.DefaultValue)];
                }
            }
            else if (webUrlParameter != null && !string.IsNullOrEmpty(webUrlParameter.DefaultValue))
            {
                using (SPSite site = new SPSite(webUrlParameter.DefaultValue))
                {
                    rootWeb = site.OpenWeb();
                }
            }
            else
            {
                rootWeb = SPContext.Current.Web;
            }

            if (includeRootWebParameter == null || includeRootWebParameter.DefaultValue.Equals("true", StringComparison.CurrentCultureIgnoreCase))
            {
                AddAllPropertiesToDataTable(rootWeb, dataTable);
            }

            if (recurseParameter == null || recurseParameter.DefaultValue.Equals("true", StringComparison.CurrentCultureIgnoreCase))
            {
                var subWebs = rootWeb.GetSubwebsForCurrentUser();
                foreach (SPWeb subWeb in subWebs)
                {
                    AddAllPropertiesToDataTable(subWeb, dataTable);
                    AddSubWebs(subWeb, dataTable);
                }
            }
            return dataTable.AsDataView();
        }

        private void AddAllPropertiesToDataTable(SPWeb web, DataTable dataTable)
        {
            EnsureDataTableColumns(web, dataTable);
            var properties = web.GetType().GetProperties();
            List<object> dataRow = new List<object>();
            foreach (var property in properties)
            {
                var value = property.GetValue(web, null);
                dataRow.Add(value == null ? null : value.ToString());
            }
            dataTable.Rows.Add(dataRow.ToArray());
        }

        private void EnsureDataTableColumns(SPWeb web, DataTable dataTable)
        {
            if (dataTable.Columns.Count == 0)
            {
                var properties = web.GetType().GetProperties();
                foreach (var property in properties)
                {
                    dataTable.Columns.Add("__sp" + property.Name, typeof(string));
                }
            }
        }

        private void AddSubWebs(SPWeb web, DataTable dataTable)
        {
            var subWebs = web.GetSubwebsForCurrentUser();
            foreach (SPWeb subWeb in subWebs)
            {
                AddAllPropertiesToDataTable(subWeb, dataTable);
                AddSubWebs(subWeb, dataTable);
            }
        }
    }
}
